Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rotation functions and diagonal/orthogonal check functions to Direction #461

Merged
merged 4 commits into from
Oct 12, 2023

Conversation

shanemadden
Copy link
Collaborator

No description provided.

/// ```
pub fn multi_rot(self, times: i8) -> Self {
let raw_dir = ((self as u8) - 1).wrapping_add_signed(times) % 8 + 1;
unsafe { std::mem::transmute(raw_dir) }
Copy link
Contributor

@asquared31415 asquared31415 Oct 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that Direction has FromPrimitive so you could instead use Direction::from_u8, and the compiler will prove that the unwrap is not necessary, except in debug mode, but that's fine to be slower.

Suggested change
unsafe { std::mem::transmute(raw_dir) }
Self::from_u8(raw_dir).unwrap()

(you may need to use num_traits::FromPrimitive;)

But if you still want to keep the unsafe, at least add a safety comment:

Suggested change
unsafe { std::mem::transmute(raw_dir) }
// SAFETY: `x % 8 + 1` is in the range of the valid values for `Direction` of 1..=8.
unsafe { std::mem::transmute(raw_dir) }

Copy link
Contributor

@asquared31415 asquared31415 Oct 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the assembly generated by the from_u8 version, it's as good as you can get and identical to the transmute.

        lea eax, [rdi + rsi]
        dec al
        and al, 7
        inc al
        ret

@shanemadden shanemadden merged commit 828a759 into rustyscreeps:main Oct 12, 2023
@shanemadden shanemadden deleted the direction_rotation branch October 12, 2023 00:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants